import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd

font_options = [
    'Microsoft YaHei',
    'SimHei',
    'FangSong',
    'KaiTi',
    'Arial Unicode MS'  # macOS 系统字体
]

plt.rcParams['font.sans-serif'] = font_options
# plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['axes.unicode_minus'] = False


def show_graph(df: pd.DataFrame):
    # 创建无向图
    G = nx.Graph()

    # 添加节点
    G.add_nodes_from(df.index)

    # 添加边
    for i, node in enumerate(df.index):
        neighbors = df.iloc[i][df.iloc[i] == 1].index.tolist()
        for neighbor in neighbors:
            G.add_edge(node, neighbor)

    # 绘制图形
    plt.figure(figsize=(8, 6))
    pos = nx.spring_layout(G)  # 布局算法
    nx.draw(G, pos, with_labels=True, node_size=800, node_color='lightblue',
            font_size=12, font_weight='bold', edge_color='gray')
    plt.title("邻接矩阵可视化")
    plt.show()


def basic_adj_matrix():
    vertices = ['1', '3', '2', '5', '4']
    # 初始化邻接矩阵
    df = pd.DataFrame([
        [0, 1, 0, 1, 0],
        [1, 0, 1, 0, 0],
        [0, 1, 0, 1, 1],
        [1, 0, 1, 0, 1],
        [0, 0, 1, 1, 0]
    ], index=vertices, columns=vertices)
    print(df)

    # 查看表结构
    show_graph(df)

    # 获取顶点个数
    node_num = len(df.index)
    # print(node_num)

    # 获取邻接矩阵
    adj_matrix = df.values
    # print(adj_matrix)

    # 获取顶点1的相邻顶点
    node_1 = adj_matrix[0]
    print(node_1)

    # 获取顶点1的相邻顶点的索引
    node_1_index = [i for i, j in enumerate(node_1) if j == 1]
    # print(node_1_index)

    # 获取顶点1的相邻顶点的索引对应的顶点
    node_1_node = [df.index[i] for i in node_1_index]
    # print(node_1_node)

    # 增加边  1、2
    df.loc['1', '2'] = 1
    df.loc['2', '1'] = 1

    # 删除边  1、2
    df.loc['1', '2'] = 0
    df.loc['2', '1'] = 0

    # 增加顶点
    df.loc['6', :] = 0
    df.loc[:, '6'] = 0
    # print(df)

    # 增加边
    df.loc['6', '1'] = 1
    df.loc['1', '6'] = 1
    # print(df)

    # show_graph(df)

    # 删除顶点
    df.drop('6', axis=0, inplace=True)
    df.drop('6', axis=1, inplace=True)
    # print(df)

    # show_graph(df)


if __name__ == '__main__':
    basic_adj_matrix()
